package naga.x.platform2.channel.qunhei.support;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.UrlBasedViewResolver;

import com.alibaba.fastjson.JSONObject;

import naga.x.platform2.app.model.RechargeTemplate;
import naga.x.platform2.channel.s399.support.S399Api;
import naga.x.platform2.channel.s399.support.S399Api.PayInfo;
import naga.x.platform2.utils.CommonUtils;
import naga.x.platform2.utils.IOUtils;
import naga.x.platform2.utils.NumberUtils;
import naga.x.platform2.utils.StringUtils;

/**
 * 群黑游戏
 * @see <a href="http://admin.qunhei.com/Upload/port/#api-User-Login">群黑游戏API</a>
 * @author yang.li
 *
 */
@Component
public class QunHeiApi {
	
	@Autowired
	private QunHeiConfig config;
	
	public enum SDKCode {
		PAY_SUCC(1, "充值成功"),
		USER_NOT_EXIST(-2, "账号不存在"),
		SIGN_ERROR(-4, "验证码错误"),
		ORDER_DUPLICATED(-5, "订单号重复"),
		;
		public final int code;
		public final String msg;
		SDKCode(int code, String msg) {
			this.code = code;
			this.msg = msg;
		}
		@Override
		public String toString() {
			return String.valueOf(code);
		}
	}
	
	public static String makeSign(String key, String[] params) {
		StringBuilder builder = new StringBuilder(64);
		for (String param : params) {
			builder.append(param);
		}
		builder.append(key);
		return CommonUtils.md5(builder.toString());
	}
	
	public String createLoginRedirectUrl(String uid, String nickname, String headimgurl) {
		StringBuilder builder = new StringBuilder(UrlBasedViewResolver.REDIRECT_URL_PREFIX);
		builder.append(config.getClientUrl())
				.append("&code=").append(S399Api.Code.SUCC.code)
				.append("&uid=").append(uid)
				.append("&nickname=").append(CommonUtils.encodeURL(nickname, IOUtils.UTF8))
				.append("&headimgurl=").append(CommonUtils.encodeURL(headimgurl, IOUtils.UTF8))
				.append("&token=1");
		return builder.toString();
	}
	
	public String createLoginErrorRedirectUrl(S399Api.Code code) {
		StringBuilder builder = new StringBuilder(UrlBasedViewResolver.REDIRECT_URL_PREFIX);
		builder.append(config.getClientUrl()).append("&code=").append(code.code).append("&msg=").append(CommonUtils.encodeURL(code.msg, IOUtils.UTF8));
		return builder.toString();
	}
	
	public Object createOrder(Integer serverId, String userId, Long playerId, String playerName, RechargeTemplate product) {
		JSONObject order = new JSONObject(8, true);
		order.put("code", S399Api.Code.SUCC.code);
//		money	Number 充值金额（单位元，整数）
		order.put("money", product.getPrice());
//		goodsName	String 充值商品名称（例：300元宝）
		order.put("goodsName", product.getName());
//		goodsId	String 充值商品id(不能重复)
		order.put("goodsId", config.getGoodsId(product.getId()));
//		gid	String 群黑平台游戏id(群黑平台开放后台游戏列表查询)
		order.put("gid", config.getGameId());
//		userId	String 充值账号(该参数是登录里面的username)
		order.put("userId", userId);
//		ext	String 充值透传参数(主要用于透传玩家服务器，可以是订单号，服务器编号之类的标识，在充值回调接口里面会原样返回,如果该参数是唯一值，需要在后台游戏里面配置)
		String ext = serverId + "|" + playerId + "|" + product.getId();
		order.put("ext", ext);
//		roleName	String 充值角色名称
		order.put("roleName", playerName);
//		sign	String 验证签名，签名方式为：MD5(money + userId + ext + key)这里的key是提交到后台的充值key,加号为连接符
		order.put("sign", makeSign(config.getPayKey(), new String[] { String.valueOf(product.getPrice()), userId, ext }));
		return order;
	}
	
	public Object createError(S399Api.Code code) {
		JSONObject error = new JSONObject(2, true);
		error.put("code", code.code);
		error.put("msg", code.msg);
		return error;
	}
	
	public static S399Api.PayInfo parsePayInfo(String ext) {
		String[] strs = StringUtils.split(ext, "|");
		if (strs == null || strs.length != 3) {
			return PayInfo.EMPTY;
		}
		int serverId = NumberUtils.parseInt(strs[0]);
		long playerId = NumberUtils.parseLong(strs[1]);
		int productId = NumberUtils.parseInt(strs[2]);
		return new PayInfo(serverId, playerId, productId);
	}
	
}
